package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

/**
 * @Description
 * @Author 王芷怡
 * @Date 2024/12/24 17:08
 **/
@Controller
@RequestMapping("/main")
public class UpdatePwd extends BaseController{
    private static final Logger LOGGER = LoggerFactory.getLogger(UpdatePwd.class);

    @Autowired
    private SysUserService sysUserService;


    //跳转到修改密码页面
    @GetMapping("/changePwd")
    public ModelAndView doSave(){
        ModelAndView mav = new ModelAndView("sys/changePwd");
        return mav;
    }

    //判断旧密码是否正确
    @ResponseBody
    @GetMapping("/oldPasswordCheck")
    public String oldPasswordCheckExist(@RequestParam String oldPassword){
        SysUser ss = (SysUser) session().getAttribute("loginUser");
        LOGGER.debug("检查密码是否正确",oldPassword,ss.getId());
        HashMap<String,Object> resultMap = new HashMap<String,Object>();
        if(StringUtils.isEmpty(oldPassword)){
            resultMap.put("pass",0);
        }else {
            try{
                SysUser sysUser = sysUserService.getByPassword(oldPassword,ss.getId());
                if(null != sysUser){
                    resultMap.put("pass",1);
                }else {
                    resultMap.put("pass",0);
                }
            }catch (Exception e){
                LOGGER.error("SysUserController中的"+"oldPasswordCheckExist方法执行发送错误。",e);
                resultMap.put("error","出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }

//    //保存或修改数据接口
    @PostMapping("/changePwd")
    public String doSave(SysUser sysUser){
        try{
            //获取登录用户信息
            SysUser ss = (SysUser) session().getAttribute("loginUser");
            //将登录这个用户的id传参
            sysUser.setId(ss.getId());
            boolean ok = sysUserService.updatePwd(sysUser);
            if(ok){
                //清空session
                session().invalidate();
                return redirect("/login");
            }
        }catch (Exception e){
            LOGGER.error("SysUserController 中的 doSave方法执行发送错误。",e);
            throw  new RuntimeException(e);
        }
        return "sys/changePwd";
    }
}
